package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.sugon.dao.SysConfigDao;
import com.sugon.entity.SysConfigEntity;
import com.sugon.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("sysConfigService")
public class SysConfigServiceImpl implements SysConfigService {

    @Resource
    private SysConfigDao sysConfigDao;

    /**
     * save
     *
     * @param config
     */
    @Override
    public void save(SysConfigEntity config) {
        config.setId(RandomUtil.randomString(32));
        config.setStatus(1);
        sysConfigDao.save(config);
    }

    /**
     * update
     *
     * @param config
     */
    @Override
    public void update(SysConfigEntity config) {
        sysConfigDao.update(config);
    }

    /**
     * updateValueByKey
     *
     * @param key
     * @param value
     */
    @Override
    public void updateValueByKey(String key, String value) {
        sysConfigDao.updateValueByKey(key, value);
    }

    /**
     * deleteBatch
     *
     * @param ids
     */
    @Override
    public void deleteBatch(String[] ids) {
        sysConfigDao.deleteBatch(ids);
    }

    /**
     * queryList
     *
     * @param map
     * @return
     */
    @Override
    public List<SysConfigEntity> queryList(Map<String, Object> map) {
        return sysConfigDao.queryList(map);
    }

    /**
     * queryTotal
     *
     * @param map
     * @return
     */
    @Override
    public int queryTotal(Map<String, Object> map) {
        return sysConfigDao.queryTotal(map);
    }

    /**
     * queryObject
     *
     * @param id
     * @return
     */
    @Override
    public SysConfigEntity queryObject(String id) {
        return sysConfigDao.queryObject(id);
    }

    /**
     * getValue
     *
     * @param key          key
     * @param defaultValue 缺省值
     * @return
     */
    @Override
    public String getValue(String key, String defaultValue) {
        String value = sysConfigDao.queryByKey(key);
        if (StringUtils.isBlank(value)) {
            return defaultValue;
        }
        return value;
    }

    /**
     * @param key   key
     * @param clazz Object对象
     * @param <T>
     * @return
     */
    @Override
    public <T> T getConfigObject(String key, Class<T> clazz) {
        String value = getValue(key, null);
        if (StringUtils.isNotBlank(value)) {
            return JSON.parseObject(value, clazz);
        }
        try {
            return clazz.newInstance();
        } catch (InstantiationException e) {
            log.error("实例化配置参数对象失败", e);
        } catch (IllegalAccessException e) {
            log.error("非法访问权限异常", e);
        }
        return null;
    }

    /**
     * getMaxLoginAttemptTime
     *
     * @return
     */
    @Override
    public int getMaxLoginAttemptTime() {
        String maxLoginAttemptTime = getValue("MAX_LOGIN_ATTEMPT_TIME", "10");
        return NumberUtil.parseInt(maxLoginAttemptTime);
    }

    /**
     * getLocalSavePath
     *
     * @return
     */
    @Override
    public String getForecaseDataPath() {
        return getValue("FORECASE_DATA_PATH", "D://");
    }

    /**
     * 配置文件服务器路径，
     * 正式环境地址：http://10.107.250.31:8113
     *
     * @return
     */
    @Override
    public String getFileServerPath() {
        return getValue("FILE_SERVER_PATH", "");
    }

    @Override
    public String getErpSynTime() {
        return getValue("ERP_SPARE_PART_SYN_TIME", "");
    }

    /**
     * getLocalSavePath
     *
     * @return
     */
    @Override
    public String getLocalSavePath() {
        return getValue("LOCAL_SAVE_PATH", "/eeomp/apk");
    }

    /**
     * 本机IP: http://10.107.250.7
     *
     * @return
     */
    @Override
    public String getHost() {
        return getValue("HOST", "");
    }

    /**
     * getPoiTemplatePath
     *
     * @return
     */
    @Override
    public String getPoiTemplatePath() {
        return getValue("POI_TEMPLATE_PATH", "/eeomp/ermsTemplate/");
    }

    /**
     * getTemSavePath
     *
     * @return
     */
    @Override
    public String getTemSavePath() {
        return getValue("TEM_SAVE_PATH", "/eeomp/ermsTemplate/");
    }

    /**
     * getBpmAppId
     *
     * @return
     */
    @Override
    public String getBpmAppId() {
        return getValue("BPM_APP_ID", "");
    }

    /**
     * getErmsAppId
     *
     * @return
     */
    @Override
    public String getErmsAppId() {
        return getValue("APPID", "");
    }

    /**
     * 远程认证中心地址
     * http://cmp.changan.com
     *
     * @return
     */
    @Override
    public String getRemoteServiceHost() {
        return getValue("REMOTE_SERVICE_HOST", "");
    }

    /**
     * getIsAuth
     *
     * @return
     */
    @Override
    public String getIsAuth() {
        return getValue("IS_AUTH", "0");
    }

    /**
     * getWorkshopTriggerTime
     *
     * @return
     */
    @Override
    public Integer getWorkshopTriggerTime() {
        return Integer.valueOf(getValue("WORKSHOP_TRIGGER_TIME", "30"));
    }

    /**
     * getFactoryTriggerTime
     *
     * @return
     */
    @Override
    public Integer getFactoryTriggerTime() {
        return Integer.valueOf(getValue("FACTORY_TRIGGER_TIME", "120"));
    }

    /**
     * 获取重新计算KPi年份
     *
     * @return
     */
    @Override
    public Integer getRecomputeKpiYears() {
        String years = getValue("RECOMPUTE_KPI_YEARS", "1");
        try {
            return Integer.valueOf(years);
        } catch (Exception ex) {
        }
        return 1;
    }

    /**
     * 设置是否显示真库存
     *
     * @return
     */
    @Override
    public Integer getIsRealSafetyStock() {
        String years = getValue("IS_REAL_SAFETY_STOCK", "1");
        try {
            return Integer.valueOf(years);
        } catch (Exception ex) {
        }
        return 1;
    }

    /**
     * getSysMsgValidDuration
     *
     * @return
     */
    @Override
    public Integer getSysMsgValidDuration() {
        String validDuration = getValue("SYS_MSG_VALID_DURATION", "14");
        return Integer.valueOf(validDuration);
    }

    /**
     * 获取产线节拍
     *
     * @param lineCode
     * @return
     */
    @Override
    public Double getPlanBeatTime(String lineCode) {
        String planBeatTimeSetting = getValue("LINE_PLAN_BEAT_TIME", "*:30");
        String pattern = planBeatTimeSetting.contains(lineCode + ":") ? lineCode + ":" : "*:";
        String planBeatTimeValue = subPlanBeatTime(planBeatTimeSetting, pattern);
        return Double.parseDouble(planBeatTimeValue);
    }

    /**
     * 获取模具节拍时间
     *
     * @param moldCode 模具编码
     * @return
     */
    @Override
    public Double getMoldBeatTime(String moldCode) {
        String planBeatTimeSetting = getValue("MOLD_BEAT", "*:30");
        String pattern = planBeatTimeSetting.contains(moldCode + ":") ? moldCode + ":" : "*:";
        String planBeatTimeValue = subPlanBeatTime(planBeatTimeSetting, pattern);
        return Double.parseDouble(planBeatTimeValue);
    }

    /**
     * 获取特种设备检测提前通知天数
     *
     * @return
     */
    @Override
    public Integer getSpecDevCheckAheadNoticeDays() {
        return Integer.valueOf(getValue("SPECIAL_DEVICE_CHECK_AHEAD_NOTICE_DAYS", "15"));
    }

    /**
     * 获取可修改维修时间的车间编码列表
     *
     * @return
     */
    @Override
    public List<String> getModifiableRepairTimeWorkshopCodeList() {
        String repairTimeModifiableWorkshopCodes = getValue("REPAIR_TIME_MODIFIABLE_WORKSHOP_CODE", "");
        return CollectionUtil.newArrayList(repairTimeModifiableWorkshopCodes.split(","));
    }

    @Override
    public String getMinioConfig() {
        return getValue("MINIO_CONFIG", "http://10.107.250.31:9000,minioadmin,FdjMinoiAdmin#@2022,erms");
    }

    @Override
    public String getProxyUrl() {
        return getValue("PROXY_URL", "");
    }

    /**
     * 从*:30,MA06:30,MA07:30,MA08:30,EA04:40原始配置字符串中截取冒号后面的时间
     * 比如pattern为MA07:，那么返回30，EA04:返回40等
     *
     * @param root    原始字符串
     * @param pattern 匹配
     * @return
     */
    private String subPlanBeatTime(String root, String pattern) {
        int patternIndex = root.indexOf(pattern);
        if (patternIndex == -1) {
            return "";
        }
        patternIndex += pattern.length();
        // 判断从patternIndex开始到位置最后是否包含逗号
        int index = root.indexOf(",", patternIndex);
        return index != -1 ? root.substring(patternIndex, index) : root.substring(patternIndex);
    }

}
